package ru.chaykin.load;
import java.io.BufferedReader;

import ru.chaykin.load.parse.MIFParser;
import ru.chaykin.rendering.CullingDataThread;
import ru.chaykin.rendering.CullingTextThread;
import ru.chaykin.rendering.CullingThread;
import android.util.Log;



public class LoadDataThread extends Thread {
	private static ILoadDataProgress ldp;
	private static IThreadException te;
	
	private volatile boolean isActive = true;	//Если false, остановим поток
	
	private CullingThread ctt = new CullingTextThread();
	private CullingThread cdt = new CullingDataThread();
	
	private String fName;
	
	public LoadDataThread(IThreadException te, ILoadDataProgress ldp, String fName) {
		super();
		this.ldp = ldp;
		this.te = te;
		this.fName = fName;
	}
	
	public static void setILoadDataProgress(IThreadException te, ILoadDataProgress ldp) {
		LoadDataThread.ldp = ldp;
		LoadDataThread.te = te;
	}
	
	private void update(final String msg) {
		ldp.post(new Runnable() {
			public void run() {
				ldp.onUpdate(msg);
			}
		});
	}
	
	private void complete() {
		ldp.post(new Runnable() {
			public void run() {
				ldp.onComplete();
			}
		});
	}
	
	private void onException(final Exception e) {
		te.runOnUiThread(new Runnable() {
			public void run() {
				te.onException(e);
			}
		});
	}
	
	public void run() {
		Log.d(getClass().getName(), "Thread started");
		String str;
		long count = 0;
		try {
			MIFParser parser = new MIFParser(fName);
			BufferedReader in = parser.getFileReader();
			
			cdt.setPriority(Thread.MIN_PRIORITY );
			cdt.start();
			ctt.setPriority(Thread.MIN_PRIORITY );
			ctt.start();
			while ((str = in.readLine()) != null && isActive) {	
				if (!parser.findLine(MIFParser.B_LINE_PATT.matcher(str))) 
					if (!parser.findPline(MIFParser.B_PLINE_PATT.matcher(str)))
						if(!parser.findRegion(MIFParser.B_REGION_PATT.matcher(str)))
							if(!parser.findText(MIFParser.B_TEXT_PATT.matcher(str)))
								if(!parser.findOther(MIFParser.B_POINT_PATT.matcher(str)))
									if(!parser.findOther(MIFParser.B_ARC_PATT.matcher(str)))
										if(!parser.findOther(MIFParser.B_RECT_PATT.matcher(str)))
											if(!parser.findOther(MIFParser.B_ROUNDRECT_PATT.matcher(str)))
												parser.findOther(MIFParser.B_ELLIPSE_PATT.matcher(str));
				
				count++;
				if (count % 25 == 0)
					update("Найдено объектов: " + parser.getObjectsCount());
			}
			in.close();
		} catch (Exception e) {
			stopThread();
			onException(e);
		}
		if (isActive)
			complete();
		Log.d(getClass().getName(), "Thread stoped");
	//	while (true);
	}
	
	public void stopThread() {
		isActive = false;
		cdt.stopThread(); //Пользователь отменил задачу
		ctt.stopThread();
	}
}
